package com.kol.collect.common.util;

/**
 * Created by liukun on 20/3/6.
 */

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import com.kol.collect.model.PayloadInfo;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@ConfigurationProperties(prefix = "config.jwt")
@Component
public class TokenUtil {
    /**
     * 根据身份ID标识，生成Token
     * 
     * @param payload
     * @return
     */
    public String getToken(PayloadInfo payload) {
        Date nowDate = new Date();
        // 过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        return Jwts.builder().setHeaderParam("typ", "JWT").setClaims(getClaims(payload)).setIssuedAt(nowDate).setExpiration(expireDate).signWith(SignatureAlgorithm.HS512, secret)
            .compact();
    }

    /**
     * 组装 claims
     * 
     * @param payload
     * @return
     */
    Map<String, Object> getClaims(PayloadInfo payload) {
        Map<String, Object> claims = new HashMap<>();
        if (StringUtils.isNotBlank(payload.getUserId())) {
            claims.put("userId", payload.getUserId());
        }
        if (StringUtils.isNotBlank(payload.getUserName())) {
            claims.put("userName", payload.getUserName());
        }
        if (StringUtils.isNotBlank(payload.getPhone())) {
            claims.put("phone", payload.getPhone());
        }

        return claims;
    }

    /**
     * 获取 Token 中注册信息
     * 
     * @param token
     * @return
     */
    public Claims getTokenClaim(String token) {
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Token 是否过期验证
     * 
     * @param expirationTime
     * @return
     */
    public boolean isTokenExpired(Date expirationTime) {
        return expirationTime.before(new Date());
    }

    private String secret;
    private long expire;
    private String header;

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public long getExpire() {
        return expire;
    }

    public void setExpire(long expire) {
        this.expire = expire;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }
}
